package com.banzhi.shop.activity;

import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.banzhi.shop.R;
import com.banzhi.shop.adapter.CartAdapter;
import com.banzhi.shop.base.BaseActivity;
import com.banzhi.shop.entity.shoppingcart.CartGoods;
import com.banzhi.shop.entity.shoppingcart.Cart_data;
import com.banzhi.shop.entity.shoppingcart.DeleteRes;
import com.banzhi.shop.entity.shoppingcart.NumRes;
import com.banzhi.shop.entity.shoppingcart.Res_Data;
import com.banzhi.shop.entity.shoppingcart.StatuRes;
import com.banzhi.shop.model.CallBack.shoppingCartCallBack;
import com.banzhi.shop.model.Impl.ChoiceShoppingCartImpl;
import com.banzhi.shop.utils.ASUtils;
import com.banzhi.shop.utils.LoadingDialogUtils;
import com.banzhi.shop.utils.NoTokenUtils;
import com.banzhi.shop.utils.NumberUtils;
import com.banzhi.shop.utils.ToastUtils;
import com.banzhi.shop.utils.Translucent;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class ChoiceShoppingCartActivity extends BaseActivity implements View.OnClickListener, shoppingCartCallBack, CartAdapter.CalculateMoneyCallBack, SwipeRefreshLayout.OnRefreshListener  {
    private ImageView ivback;
    private ListView listView;
   // private IshoppingCartModel model;
    private Cart_data cartdata;
    private CartAdapter adapter;
    private List<CartGoods> cartgoods = new ArrayList<>();
    /**
     * 用于保存  传过来改变的是Listview的哪个item
     */
    private int position;
    /**
     * 传过来的 选中状态
     */
    private String selected;
    private SwipeRefreshLayout srllistview;
    /**
     * 全选
     */
    private ImageView ivcheck;
    /**
     * 用来判断全选按钮是不是被选中了
     */
    private boolean isALLcheck;
    /**
     * 总价
     */
    private TextView tvallprice;
    /**
     * 结算
     */
    private TextView tvjiesuan;
    private int page = 1;
    /**
     * 判断listview是不是滑到最低端了
     */
    private boolean isbottom;

    private RelativeLayout rlnodata;
    /**
     * 判断是不是至少有一个商品被选中
     */
    private boolean ischeck;
    private ChoiceShoppingCartImpl model;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choice_shopping_cart);
        Translucent.setTranslucent(this);
        setinits();
        setListeners();
        //model = new shoppingCartImpl();
        model = new ChoiceShoppingCartImpl();
        LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
        this.model.getData(page, this);

    }
    @Override
    protected void onRestart() {
        super.onRestart();
        LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
        model.getData(page, this);
    }

    private void setinits() {
        ivback = (ImageView) findViewById(R.id.iv_back);
        listView = (ListView) findViewById(R.id.listview);
        srllistview = (SwipeRefreshLayout) findViewById(R.id.srl_listview);
        srllistview.setColorSchemeResources(R.color.themeColor);
        srllistview.setProgressBackgroundColorSchemeResource(R.color.colorWhite);
        srllistview.setOnRefreshListener(this);

        ivcheck = (ImageView) findViewById(R.id.iv_check);
        tvallprice = (TextView) findViewById(R.id.tv_allprice);
        tvjiesuan = (TextView) findViewById(R.id.tv_jiesuan);
        rlnodata = (RelativeLayout) findViewById(R.id.rl_nodata);
    }

    private void setListeners() {
        ivback.setOnClickListener(this);
        ivcheck.setOnClickListener(this);
        tvjiesuan.setOnClickListener(this);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if ("1".equals(cartgoods.get(position).getIsregistergoods())) {
                    ToastUtils.makeToastShort("该商品为注册商品");
                } else if ("0".equals(cartgoods.get(position).getStatus())) {
                    ToastUtils.makeToastShort("该商品已下架");
                } else if ("1".equals(cartgoods.get(position).getDeleted())) {
                    ToastUtils.makeToastShort("该商品已删除");
                } else {
                    Intent intent = null;
                    if ("1".equals(cartgoods.get(position).getIsagentgoods())) {
                      //  intent = new Intent(ChoiceShoppingCartActivity.this, CommodityDetails_DZZQActivity.class);
                    } else {
                        intent = new Intent(ChoiceShoppingCartActivity.this, ChoicesDetailsActivity.class);
                    }
                    intent.putExtra("id", cartgoods.get(position).getGoodsid());
                    startActivity(intent);
                }
            }
        });
        listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && isbottom) {
                    page++;
                    LoadingDialogUtils.showProgress(ChoiceShoppingCartActivity.this, "正在加载,请稍后~");
                    model.getData(page, ChoiceShoppingCartActivity.this);
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
                    isbottom = true;
                } else {
                    isbottom = false;
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_check:
                if (cartgoods.size() == 0) {
                    return;
                }
                if (!isALLcheck) {
                    LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
                    model.changeAllStatu("1", this);
                }
                break;
            case R.id.tv_jiesuan:
                if (cartgoods.size() == 0) {
                    ToastUtils.makeToastShort("购物车还没有商品，请前往店铺选购吧！");
                } else {
                    for (int i = 0; i < cartgoods.size(); i++) {
                        if ("1".equals(cartgoods.get(i).getSelected())) {
                            ischeck = true;
                            break;
                        }
                    }
                    if (ischeck) {
                        LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
                        model.QueRenOrder(this);
                    } else {
                        ToastUtils.makeToastShort("请至少选择一个商品进行结算");
                    }
                }

                break;
        }
    }

    /**
     * 获取购物车详情后展示页面
     */
    private void showViews(String str) {
        tvallprice.setText(NumberUtils.DecimalFormat(str));
        for (int i = 0; i < cartgoods.size(); i++) {
            if ("0".equals(cartgoods.get(i).getSelected())) {
                isALLcheck = false;
                break;
            } else {
                isALLcheck = true;
            }
        }

        if (isALLcheck) {
            ivcheck.setImageResource(R.mipmap.gouxuan);
        } else {
            ivcheck.setImageResource(R.mipmap.tuoyuan);
        }

    }

    /**
     * 获取购物车信息成功
     */
    @Override
    public void ongetDataSuccess(Object object) {
        cartdata = (Cart_data) object;


        if (srllistview.isRefreshing()) {
            srllistview.setRefreshing(false);
        }
        LoadingDialogUtils.dismiss();
        if (page == 1) {
            cartgoods.clear();
        } else {
            if (cartdata.getCartGoods().size() == 0) {
//                ToastUtils.makeToastShort("没有更多了");
                return;
            }
        }
        cartgoods.addAll(cartdata.getCartGoods());

        showViews(cartdata.getSelectGoodsSum());
//        ToastUtils.makeToastShort("dadasdad");
        if (cartgoods.size() == 0) {
            rlnodata.setVisibility(View.VISIBLE);
        } else {
            rlnodata.setVisibility(View.GONE);
        }
        if (adapter == null) {
            adapter = new CartAdapter(this, cartgoods);
            listView.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
        adapter.CartCallBack(this);

    }


    /**
     * 获取购物车信息失败
     */
    @Override
    public void ongetDataError(Object object) {
        if (srllistview.isRefreshing()) {
            srllistview.setRefreshing(false);
        }
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    /**
     * @param object 改变购物车商品数量成功的返回
     */
    @Override
    public void changeNumberSuccess(Object object) {
        LoadingDialogUtils.dismiss();
        NumRes res = (NumRes) object;
        if (ASUtils.isCanUse(res.getSelectGoodsSum())) {
            tvallprice.setText(NumberUtils.DecimalFormat(res.getSelectGoodsSum()));
        }
        cartgoods.get(position).setTotal(res.getGoodInfo().getTotal());
        adapter.notifyDataSetChanged();
    }

    /**
     * @param object 改变购物车商品数量失败的返回
     */
    @Override
    public void changeNumverError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    /**
     * @param object 改变商品的选中状态成功
     */
    @Override
    public void changeStatuSuccess(Object object) {
        LoadingDialogUtils.dismiss();
        StatuRes res = (StatuRes) object;
        cartgoods.get(position).setSelected(selected);
        showViews(res.getSelectGoodsSum());
        adapter.notifyDataSetChanged();
    }

    /**
     * @param object 改变商品的选中状态失败
     */
    @Override
    public void changeStatuError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    /**
     * @param object 全选成功
     */
    @Override
    public void changeAllStatuSuccess(Object object) {
        StatuRes res = (StatuRes) object;
        if (ASUtils.isCanUse(res.getSelectGoodsSum())) {
            tvallprice.setText(NumberUtils.DecimalFormat(res.getSelectGoodsSum()));
        }
        LoadingDialogUtils.dismiss();
        if (!isALLcheck) {
            isALLcheck = true;
            ivcheck.setImageResource(R.mipmap.gouxuan);
            for (int i = 0; i < cartgoods.size(); i++) {
                cartgoods.get(i).setSelected("1");
            }
        }
        adapter.notifyDataSetChanged();
    }

    /**
     * @param object 全选失败
     */
    @Override
    public void changeAllStatuError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    /**
     * @param object 删除商品成功
     */
    @Override
    public void deleteGoodsSuccess(Object object) {
        DeleteRes res = (DeleteRes) object;
        if (ASUtils.isCanUse(res.getSelectGoodsSum())) {
            tvallprice.setText(NumberUtils.DecimalFormat(res.getSelectGoodsSum()));
        }
        cartgoods.remove(position);

        if (cartgoods.size() == 0) {
            rlnodata.setVisibility(View.VISIBLE);
        } else {
            rlnodata.setVisibility(View.GONE);
        }

        adapter.notifyDataSetChanged();
    }

    /**
     * @param object 删除商品失败
     */
    @Override
    public void deleteGoodsError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    /**
     * @param object 确认订单成功
     */
    @Override
    public void QueRenOrderSuccess(Object object) {
        LoadingDialogUtils.dismiss();
        Res_Data data = (Res_Data) object;

       // Intent intent = new Intent(this, OrderAffirmCartActivity.class);
        Intent intent = new Intent(this, ChoiceOrderAffirmCartActivity.class);
        intent.putExtra("data", data);
        startActivity(intent);
    }

    /**
     * @param object 确认订单失败
     */
    @Override
    public void QueRenOrderError(Object object) {
        JSONObject jsonObject = (JSONObject) object;
        NoTokenUtils.loginOut(this, jsonObject);
        ToastUtils.makeToastShort(jsonObject.optString("msg"));
    }

    /**
     * @param number adapter的回调，用于点击加减商品数量后在activity发请求操作界面的更新
     */
    @Override
    public void changeNum(int number, int position) {
        LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
        model.changeNumber(cartgoods.get(position).getCart_id(), number, this);
        this.position = position;
    }

    /**
     * @param position adapter的回调，用于选中商品和取消选中商品在activity发请求操作界面的更新
     */
    @Override
    public void changeState(String selected, int position) {
        LoadingDialogUtils.showProgress(this, "正在加载,请稍后~");
        model.changeStatu(cartgoods.get(position).getCart_id(), selected, this);
        this.position = position;
        this.selected = selected;
    }

    /**
     * @param position adapter的回调，用于删除商品在activity发请求操作界面的更新
     */
    @Override
    public void deleteGoods(int position) {
        showSharePopupwindow(position);

    }

    /**
     * 点击删除提示下是不是确定删除
     */
    private void showSharePopupwindow(final int position) {
        //设置contentView
        View contentView = LayoutInflater.from(ChoiceShoppingCartActivity.this).inflate(R.layout.popupwindow_delete_goods, null);
        final PopupWindow popWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);
        popWindow.setContentView(contentView);
//        popWindow.setAnimationStyle(R.style.AnimBottom);

        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(false);// 设置允许在外点击消失
        //设置各个控件的点击响应
        TextView tvcancle = (TextView) contentView.findViewById(R.id.tv_cancle);
        TextView tvtrue = (TextView) contentView.findViewById(R.id.tv_true);
        RelativeLayout rlbackground = (RelativeLayout) contentView.findViewById(R.id.rl_background);
        LinearLayout ll = (LinearLayout) contentView.findViewById(R.id.ll);
        rlbackground.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        tvcancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        tvtrue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LoadingDialogUtils.showProgress(ChoiceShoppingCartActivity.this, "正在加载,请稍后~");
                model.deleteGoods(cartgoods.get(position).getCart_id(), ChoiceShoppingCartActivity.this);
                ChoiceShoppingCartActivity.this.position = position;
                popWindow.dismiss();
            }
        });
        popWindow.showAtLocation(contentView, Gravity.CENTER | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    @Override
    public void onRefresh() {
        page = 1;
        model.getData(page, this);
    }
}
